<template lang="html">
  <div class="wangeditor">
    <el-upload :action="uploadUrl" :before-upload="handleBeforeUpload" :on-success="handleUploadSuccess"
      :on-error="handleUploadError" name="file" :show-file-list="false" :headers="headers" style="display: none"
      ref="upload">
    </el-upload>

    <div ref="toolbar" class="toolbar"></div>
    <div ref="wangeditor" class="text"></div>
  </div>
</template>

<script>
import axios from "axios"
import { getToken } from "@/utils/auth"

import E from "wangeditor";
export default {
  data() {
    return {
      wangEditor: null,
      wangEditorInfo: null,
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传地址
      headers: {
        Authorization: "Bearer " + getToken()
      },
      fileSize: 5, // 文件大小限制(MB)
    };
  },
  model: {
    prop: "value",
    event: "change"
  },
  props: {
    value: {
      type: String,
      default: ""
    },
    isClear: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    isClear(val) {
      // 触发清除文本域内容
      if (val) {
        this.wangEditor.txt.clear();
        this.wangEditorInfo = null;
      }
    },
    value: function (value) {
      if (value !== this.wangEditor.txt.html()) {
        this.isClear = false;
        this.wangEditor.txt.html(this.value); //value为编辑框输入的内容，这里我监听了一下值，当父组件调用得时候，如果给value赋值了，子组件将会显示父组件赋给的值
      }
    }
  },
  mounted() {
    this.initEditor();
    this.wangEditor.txt.html(this.value);
    // 添加粘贴事件监听
    this.$refs.wangeditor.addEventListener('paste', this.handlePasteImage, true)
  },
  beforeDestroy() {
    // 移除事件监听
    this.$refs.wangeditor.removeEventListener('paste', this.handlePasteImage)
  },
  methods: {
    initEditor() {
      this.wangEditor = new E(this.$refs.toolbar, this.$refs.wangeditor);
      this.wangEditor.customConfig = this.wangEditor.customConfig ? this.wangEditor.customConfig : this.wangEditor.config
      this.wangEditor.customConfig.uploadImgShowBase64 = true; // base64存储图片（推荐）
      //this.wangEditor.customConfig.uploadImgServer = "https://jsonplaceholder.typicode.com/posts/"; // 配置服务器端地址（不推荐）
      this.wangEditor.customConfig.uploadImgHeaders = {}; // 自定义header
      this.wangEditor.customConfig.uploadFileName = "file"; // 后端接受上传文件的参数名
      this.wangEditor.customConfig.uploadImgMaxSize = 2 * 1024 * 1024; // 将图片大小限制为（默认最大支持2M）
      this.wangEditor.customConfig.uploadImgMaxLength = 6; // 限制一次最多上传6张图片
      this.wangEditor.customConfig.uploadImgTimeout = 1 * 60 * 1000; // 设置超时时间（默认1分钟）

      // 自定义图片上传
      this.wangEditor.customConfig.customUploadImg = (files, insert) => {
        const formData = new FormData();
        files.forEach(file => {
          if (this.handleBeforeUpload(file)) {
            formData.append('file', file);
            axios.post(this.uploadUrl, formData, {
              headers: {
                "Content-Type": "multipart/form-data",
                Authorization: this.headers.Authorization
              }
            }).then(res => {
              if (res.data.code === 200) {
                insert(process.env.VUE_APP_BASE_API + res.data.fileName)
              } else {
                this.$message.error("图片上传失败")
              }
            }).catch(() => {
              this.$message.error("图片上传失败")
            })
          }
        })
      }

      // 配置菜单
      this.wangEditor.customConfig.menus = [
        "head", // 标题
        "bold", // 粗体
        "fontSize", // 字号
        "fontName", // 字体
        "italic", // 斜体
        "underline", // 下划线
        "strikeThrough", // 删除线
        "table", // 表格
        "foreColor", // 文字颜色
        "backColor", // 背景颜色
        // "link", // 插入链接
        "list", // 列表
        'unorderedList', //无序列表
        "justify", // 对齐方式
        "quote", // 引用
        // "emoticon", // 表情
        "image", // 插入图片
        // "video", // 插入视频
        // "code", // 插入代码
        "undo", // 撤销
        "redo", // 重复
        "fullscreen" // 全屏
      ];
      this.wangEditor.customConfig.uploadImgHooks = {
        fail: (xhr, editor, result) => {
          // 插入图片失败回调
        },
        success: (xhr, editor, result) => {
          // 图片上传成功回调
        },
        timeout: (xhr, editor) => {
          // 网络超时的回调
        },
        error: (xhr, editor) => {
          // 图片上传错误的回调
        },
        customInsert: (insertImg, result, editor) => {
          // 图片上传成功，插入图片的回调（不推荐）
          insertImg(result.url);
        }
      };
      this.wangEditor.customConfig.onchange = html => {
        this.wangEditorInfo = html;
        this.$emit("change", this.wangEditorInfo); // 将内容同步到父组件中
      };
      // 创建富文本编辑器
      this.wangEditor.create();
    },

    // 上传前校验
    handleBeforeUpload(file) {
      const type = ["image/jpeg", "image/jpg", "image/png", "image/svg"]
      const isJPG = type.includes(file.type)
      if (!isJPG) {
        this.$message.error(`图片格式错误!`)
        return false
      }
      const isLt = file.size / 1024 / 1024 < this.fileSize
      if (!isLt) {
        this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`)
        return false
      }
      return true
    },

    // 上传成功
    handleUploadSuccess(res) {
      if (res.code === 200) {
        this.$message.success("图片上传成功")
      } else {
        this.$message.error("图片上传失败")
      }
    },

    // 上传失败
    handleUploadError() {
      this.$message.error("图片上传失败")
    },

    // 处理粘贴图片
    handlePasteImage(e) {
      const clipboard = e.clipboardData || window.clipboardData
      if (clipboard && clipboard.items) {
        for (let i = 0; i < clipboard.items.length; i++) {
          const item = clipboard.items[i]
          if (item.type.indexOf('image') !== -1) {
            e.preventDefault()
            const file = item.getAsFile()
            if (file && this.handleBeforeUpload(file)) {
              const formData = new FormData()
              formData.append("file", file)
              axios.post(this.uploadUrl, formData, {
                headers: {
                  "Content-Type": "multipart/form-data",
                  Authorization: this.headers.Authorization
                }
              }).then(res => {
                if (res.data.code === 200) {
                  this.wangEditor.cmd.do('insertImage', process.env.VUE_APP_BASE_API + res.data.fileName)
                }
              })
            }
          }
        }
      }
    }
  }
};
</script>

<style lang="scss">
.wangeditor {
  position: relative;
  z-index: 1;
  border: 1px solid #e6e6e6;
  box-sizing: border-box;

  .toolbar {
    border-bottom: 1px solid #e6e6e6;
    box-sizing: border-box;
  }

  .text {
    min-height: 300px;
  }
}

ul li {
  list-style-type: disc;
  /* disc 表示实心圆点，你可以根据需要选择其他类型，如 square、circle 等 */
}
</style>